<?php
if(!session_id()) { session_start(); }
include_once('db.class.php');
class Contact {

	const SUCCESS = 800;
	const FAIL = 0;
	const DATA_EXISTS = 1;
	private $title;
	private $message;
	
	function getTitle() {
		return $this->title;
	}
	
	function getMessage() {
		return $this->message;
	}
	
	function readMessage($id) {
		$db = new db();
		$results = $db->select("SELECT users.username, contacts.contact_message FROM contacts INNER JOIN users WHERE contacts.user_id = users.user_id AND contact_ticket_id = '$id' ORDER BY contact_unix_time");
		if($results != 0) {
			return $results;
		}
		return self::FAIL;
	}
	
	function addReply($ticket, $message) {
		$db = new db();
		$user_id = $_SESSION['user_id'];
		$time = time();
		$results = $db->insert("INSERT INTO contacts(contact_ticket_id, user_id, contact_message, contact_unix_time) VALUES('$ticket', '$user_id', '$message', '$time')");
		$results2 = $db->update("UPDATE contact_tickets SET contact_ticket_update = '$time', contact_ticket_read = '0' WHERE contact_ticket_id = '$ticket'");
		return self::SUCCESS;
	}
	
	function setOwner($ticket) {
		$db = new db();
		$user_id = $_SESSION['user_id'];
		$result = $db->select("SELECT contact_ticket_admin_id FROM contact_tickets WHERE contact_ticket_id = '$ticket'");
		if($result != 0) {
			if($result[0]['contact_ticket_admin_id'] == null) {
				$updater = $db->update("UPDATE contact_tickets SET contact_ticket_admin_id = '$user_id' WHERE contact_ticket_id = '$ticket'");
			}
		}
	}
	
	function retrieveNewMessages() {
		$db = new db();
		$user_id = $_SESSION['user_id'];
		$results = $db->select("SELECT * FROM contact_tickets WHERE contact_ticket_admin_id IS NULL AND contact_ticket_status = '1' ORDER BY contact_ticket_update");
		if($results != 0) {
			return $results;
		}
		return 0;
	}
	
	function closeContact($id) {
		$db = new db();
		$results = $db->update("UPDATE contact_tickets SET contact_ticket_status = '0' WHERE contact_ticket_id = '$id'");
		if($results) {
			return 800;
		}
		return 0;
	}
	
	function add($message, $title) {
		$db = new db();
		$user_id = $_SESSION['user_id'];
		$time = time();
		$results = $db->insert("INSERT INTO contact_tickets(contact_ticket_title, contact_ticket_user_id, contact_ticket_update) VALUES('$title', '$user_id', '$time')");
		if($results) {
			$message_in = $db->insert("INSERT INTO contacts(contact_ticket_id, user_id, contact_message, contact_unix_time) VALUES('$results', '$user_id', '$message', '$time')");
			if($message_in) {
				return 800;
			}
		}
		return -1;
	}
}
?>